package com.qdxht.dispenser.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

import com.hjq.toast.ToastUtils;
import com.qdxht.dispenser.R;
import com.qdxht.dispenser.base.BaseActivity;
import com.qdxht.dispenser.databinding.ActivityMqttTestBinding;
import com.qdxht.dispenser.service.MqttManagerService;
import com.qdxht.dispenser.utils.MqttUtil;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import timber.log.Timber;

/**
 * MQTT测试页面
 */
public class MqttTestActivity extends BaseActivity<ActivityMqttTestBinding> {

    private EditText etMqttServer;
    private EditText etMqttUsername;
    private EditText etMqttPassword;
    private Button btnConnect;
    private Button btnDisconnect;
    private EditText etSubscribeTopic;
    private Button btnSubscribe;
    private EditText etPublishTopic;
    private EditText etMessage;
    private Button btnPublish;
    private TextView tvLog;
    private Button btnClearLog;

    private boolean isConnected = false;

    // 用于处理MQTT事件的回调
    private final MqttManagerService.MqttEventCallbackAdapter mqttEventCallback = new MqttManagerService.MqttEventCallbackAdapter() {
        @Override
        public void onConnectComplete(boolean reconnect, String serverURI) {
            appendLog("连接完成" + (reconnect ? " (重连)" : "") + ": " + serverURI);
        }

        @Override
        public void onConnectSuccess() {
            runOnUiThread(() -> {
                isConnected = true;
                updateConnectionStatus(true);
                appendLog("连接成功");
                ToastUtils.show("MQTT连接成功");
            });
        }

        @Override
        public void onConnectFailure(Throwable cause) {
            runOnUiThread(() -> {
                isConnected = false;
                updateConnectionStatus(false);
                appendLog("连接失败: " + cause.getMessage());
                ToastUtils.show("MQTT连接失败: " + cause.getMessage());
            });
        }

        @Override
        public void onConnectionLost(Throwable cause) {
            runOnUiThread(() -> {
                isConnected = false;
                updateConnectionStatus(false);
                appendLog("连接断开: " + cause.getMessage());
                ToastUtils.show("MQTT连接断开");
            });
        }

        @Override
        public void onMessageArrived(String topic, MqttMessage message) {
            String payload = new String(message.getPayload());
            appendLog("接收 [" + topic + "]: " + payload);
        }

        @Override
        public void onDeliveryComplete(IMqttDeliveryToken token) {
            appendLog("消息发送完成");
        }

        @Override
        public void onSubscribeSuccess(String topic) {
            appendLog("订阅成功: " + topic);
            runOnUiThread(() -> ToastUtils.show("订阅主题成功: " + topic));
        }

        @Override
        public void onSubscribeFailure(String topic, Throwable cause) {
            appendLog("订阅失败: " + topic + ", 原因: " + cause.getMessage());
            runOnUiThread(() -> ToastUtils.show("订阅失败: " + cause.getMessage()));
        }

        @Override
        public void onPublishSuccess(String topic) {
            appendLog("发布成功: " + topic);
        }

        @Override
        public void onPublishFailure(String topic, Throwable cause) {
            appendLog("发布失败: " + topic + ", 原因: " + cause.getMessage());
            runOnUiThread(() -> ToastUtils.show("发布失败: " + cause.getMessage()));
        }
    };


    public static void start(Context context) {
        Intent intent = new Intent(context, MqttTestActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected ActivityMqttTestBinding getBinding() {
        return ActivityMqttTestBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        // 初始化视图
        etMqttServer = binding.etMqttServer;
        etMqttUsername = binding.etMqttUsername;
        etMqttPassword = binding.etMqttPassword;
        btnConnect = binding.btnMqttConnect;
        btnDisconnect = binding.btnMqttDisconnect;
        etSubscribeTopic = binding.etMqttSubscribeTopic;
        btnSubscribe = binding.btnMqttSubscribe;
        etPublishTopic = binding.etMqttPublishTopic;
        etMessage = binding.etMqttMessage;
        btnPublish = binding.btnMqttPublish;
        tvLog = binding.tvMqttLog;
        btnClearLog = binding.btnClearLog;

        // 设置日志TextView能够滚动
        tvLog.setMovementMethod(new ScrollingMovementMethod());

        // 设置按钮点击事件
        btnConnect.setOnClickListener(v -> connect());
        btnDisconnect.setOnClickListener(v -> disconnect());
        btnSubscribe.setOnClickListener(v -> subscribeTopic());
        btnPublish.setOnClickListener(v -> publishMessage());
        btnClearLog.setOnClickListener(v -> clearLog());
    }

    @Override
    protected void initData() {
        initMqtt();
    }

    private void initMqtt() {
        // 初始化MQTT工具
        MqttUtil.init(this,mqttEventCallback);

        // 如果已经连接，更新UI状态
        if (MqttUtil.isConnected()) {
            isConnected = true;
            updateConnectionStatus(true);
            appendLog("MQTT已连接");
        }
    }

    private void connect() {
        String serverUri = etMqttServer.getText().toString().trim();
        String username = etMqttUsername.getText().toString().trim();
        String password = etMqttPassword.getText().toString().trim();
        
        if (TextUtils.isEmpty(serverUri)) {
            ToastUtils.show("请输入服务器地址");
            return;
        }
        
        // 生成客户端ID
        String clientId = "AndroidDispenserApp_" + UUID.randomUUID().toString();
        
        appendLog("正在连接到 " + serverUri + "...");
        
        // 配置MQTT
        MqttUtil.configureMqtt(
                serverUri,
                clientId,
                username.isEmpty() ? null : username,
                password.isEmpty() ? null : password
        );
        
        // 连接
        if (MqttUtil.connect()) {
            btnConnect.setEnabled(false);
            appendLog("MQTT连接请求已发送");
        } else {
            appendLog("MQTT连接请求发送失败");
            ToastUtils.show("连接请求失败");
        }
    }

    private void disconnect() {
        MqttUtil.disconnect();
        isConnected = false;
        updateConnectionStatus(false);
        appendLog("已断开连接");
    }

    private void subscribeTopic() {
        if (!isConnected) {
            ToastUtils.show("MQTT未连接");
            return;
        }
        
        String topic = etSubscribeTopic.getText().toString().trim();
        if (TextUtils.isEmpty(topic)) {
            ToastUtils.show("请输入订阅主题");
            return;
        }
        
        // 订阅主题，QoS设为1
        if (MqttUtil.subscribe(topic, 1)) {
            appendLog("正在订阅主题: " + topic);
        } else {
            appendLog("订阅请求失败: " + topic);
            ToastUtils.show("订阅请求失败");
        }
    }

    private void publishMessage() {
        if (!isConnected) {
            ToastUtils.show("MQTT未连接");
            return;
        }
        
        String topic = etPublishTopic.getText().toString().trim();
        String message = etMessage.getText().toString().trim();
        
        if (TextUtils.isEmpty(topic)) {
            ToastUtils.show("请输入发布主题");
            return;
        }
        
        if (TextUtils.isEmpty(message)) {
            ToastUtils.show("请输入消息内容");
            return;
        }
        
        // 发布消息，QoS设为1，不保留
        if (MqttUtil.publish(topic, message, 1, false)) {
            appendLog("发送 [" + topic + "]: " + message);
        } else {
            appendLog("发送失败: " + topic);
            ToastUtils.show("发送请求失败");
        }
    }

    private void updateConnectionStatus(boolean connected) {
        btnConnect.setEnabled(!connected);
        btnDisconnect.setEnabled(connected);
        btnSubscribe.setEnabled(connected);
        btnPublish.setEnabled(connected);
    }

    private void appendLog(final String message) {
        runOnUiThread(() -> {
            if(tvLog.getLayout() == null){
                return;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
            String time = sdf.format(new Date());
            String logMessage = time + " - " + message + "\n";
            
            tvLog.append(logMessage);
            
            // 自动滚动到底部
            int scrollAmount = tvLog.getLayout().getLineTop(tvLog.getLineCount()) - tvLog.getHeight();
            if (scrollAmount > 0) {
                tvLog.scrollTo(0, scrollAmount);
            } else {
                tvLog.scrollTo(0, 0);
            }
        });
    }

    private void clearLog() {
        tvLog.setText("");
    }

    @Override
    protected void onDestroy() {
        // 移除回调
        MqttUtil.removeMqttEventCallback(mqttEventCallback);
        
        // 释放MQTT服务
        MqttUtil.release(this);
        
        super.onDestroy();
    }
} 